package com.train.gateway.common.utils.io;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.train.common.utils.exception.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.ByteBuffer;

@Slf4j
public class IoUtils {

    /**
     * 响应数据
     * @param response
     * @param data
     * @return
     * @param <T>
     */
    public static <T> Mono<Void> write(ServerHttpResponse response, T data) {
        response.getHeaders().set("content-type", "application/json;charset=utf-8");
        ByteBuffer buffer = null;
        try {
            buffer = ByteBuffer.wrap(new ObjectMapper().writeValueAsBytes(data));
        } catch (JsonProcessingException e) {
            log.error("{}", ExceptionUtils.getExpMsg(e));
        }
        DataBufferFactory factory = new DefaultDataBufferFactory();
        if (buffer == null) {
            return Mono.empty();
        }
        DataBuffer wrap = factory.wrap(buffer);
        return response.writeWith(Mono.just(wrap));
    }
}
